package com.mdxx.xczd.ui.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.mdxx.xczd.R;
import com.mdxx.xczd.app.App;
import com.mdxx.xczd.app.ConstantsValue;
import com.mdxx.xczd.app.UrlValue;
import com.mdxx.xczd.bean.FinishedPoint;
import com.mdxx.xczd.bean.IceNums;
import com.mdxx.xczd.bean.MessageEvent;
import com.mdxx.xczd.bean.PatrolPointBean;
import com.mdxx.xczd.bean.Point;
import com.mdxx.xczd.bean.PushExtrasDataBean;
import com.mdxx.xczd.bean.TaskBean;
import com.mdxx.xczd.bean.VideoBean;
import com.mdxx.xczd.db.bo.LocationDataBO;
import com.mdxx.xczd.db.bo.VideoDataBO;
import com.mdxx.xczd.db.cache.CacheDeta;
import com.mdxx.xczd.imp.TimeEnd;
import com.mdxx.xczd.manager.AudioManagerUtil;
import com.mdxx.xczd.manager.RtspMenager;
import com.mdxx.xczd.manager.SynthesizerManager;
import com.mdxx.xczd.receiver.BatteryReceiver;
import com.mdxx.xczd.service.GuardService;
import com.mdxx.xczd.service.LocationService;
import com.mdxx.xczd.service.LoopCallService;
import com.mdxx.xczd.ui.base.BaseActivity;
import com.mdxx.xczd.ui.contract.TaskContract;
import com.mdxx.xczd.ui.model.TaskModel;
import com.mdxx.xczd.ui.presenter.TaskPresenter;
import com.mdxx.xczd.utils.DialogUtil;
import com.mdxx.xczd.utils.DistanceUtil;
import com.mdxx.xczd.utils.FormatUtil;
import com.mdxx.xczd.utils.GsonUtil;
import com.mdxx.xczd.utils.NetworkUtil;
import com.mdxx.xczd.utils.SPUtil;
import com.mdxx.xczd.utils.ToastUtil;
import com.mdxx.xczd.widget.AutoScrollTextView;
import com.mdxx.xczd.widget.LocationView;
import com.mdxx.xczd.widget.TimerTextView;
import com.orhanobut.logger.Logger;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.BindView;
import butterknife.OnClick;

/**
 *
 */
public class TaskActivity extends BaseActivity<TaskPresenter, TaskModel> implements
        TaskContract.View{

    @BindView(R.id.tv_task_empty)
    TextView tv_task_empty;

    @BindView(R.id.tv_name)
    TextView tv_name;

    @BindView(R.id.tv_radius)
    TextView tv_radius;

    @BindView(R.id.rl_title)
    RelativeLayout rl_title;

    @BindView(R.id.ll_being_task1)
    LinearLayout ll_being_task1;

    @BindView(R.id.tv_being_task_route1)
    TextView tv_being_task_route1;

    @BindView(R.id.tv_being_task_time1)
    TextView tv_being_task_time1;

    @BindView(R.id.tv_being_task_percentage1)
    TextView tv_being_task_percentage1;

    @BindView(R.id.ttv_being_task_time1)
    TimerTextView ttv_being_task_time1;

    @BindView(R.id.ll_being_task2)
    LinearLayout ll_being_task2;

    @BindView(R.id.tv_being_task_route2)
    TextView tv_being_task_route2;

    @BindView(R.id.tv_being_task_time2)
    TextView tv_being_task_time2;

    @BindView(R.id.tv_being_task_percentage2)
    TextView tv_being_task_percentage2;

    @BindView(R.id.ttv_being_task_time2)
    TimerTextView ttv_being_task_time2;

    @BindView(R.id.ll_task1)
    LinearLayout ll_task1;

    @BindView(R.id.tv_task_route1)
    TextView tv_task_route1;

    @BindView(R.id.tv_task_time1)
    TextView tv_task_time1;

    @BindView(R.id.ll_task2)
    LinearLayout ll_task2;

    @BindView(R.id.tv_task_route2)
    TextView tv_task_route2;

    @BindView(R.id.tv_task_time2)
    TextView tv_task_time2;

    @BindView(R.id.custom_locationview1)
    LocationView custom_locationview1;

    @BindView(R.id.custom_locationview2)
    LocationView custom_locationview2;

    @BindView(R.id.tv_quiet_alram)
    TextView tv_quiet_alram;

    @BindView(R.id.ib_task_more)
    ImageButton ib_task_more;

    @BindView(R.id.iv_weixing)
    ImageView iv_weixing;

    @BindView(R.id.tv_task_auto)
    AutoScrollTextView autoScrollTextView;

    private boolean isSpeak = false;
    private boolean isLock = false;
    private boolean shortPress = false;
    private boolean isAlarm = false;
    private boolean isAutom = false;
    private File file;
    private String imag_path;
    private String video_path;
    private final static int TAKEPHOTO = 0x01;
    private final static int TAKEVIDEO = 0x02;
    private final static int ICE = 0x03;
    private List<TaskBean> taskList = new ArrayList<TaskBean>();
    private List<TaskBean> orderList = new ArrayList<TaskBean>();
    private CacheDeta cache ;
    private Timer timer = new Timer();
    private List<Task> listTask = new ArrayList<Task>();
    private AlarmTask alarmTask = new AlarmTask();
    private List<PatrolPointBean> listUnfinish ;
    private final static int TYPE_PUSH = 0x01;
    private final static int TYPE_NETWORK = 0x02;
    private final static int TYPE_NETWORK_WIFI = 0x04;
    private final static int TYPE_SERVICELOCATION = 0x03;
    private final static int TYPE_LOGOUT = 0x05;
    private final static int TYPE_SCREEM_LOCK = 0x06;
    private final static int TYPE_ONLINE= 0x07;
    private final static int TYPE_DROPPED = 0x08;
    private final static int TYPE_NO_NETWORK = 0x09;
    private final static int TYPE_DEL_DEV= 10;
    private final static int TYPE_LOCK_DEV = 11;
    List<IceNums> iceList ;
    private int current = 0;

    private LoopCallService.MyBinder mBinder;
    private Conn conn;

    private boolean isICEStart = false;
    private long exitTime = 0;

    private SynthesizerManager synthesizerManager;
    private  AudioManagerUtil audioManager;
    private RtspMenager rtspMenager;
    BatteryReceiver batteryReceiver = new BatteryReceiver();  //电量广播
    private List<Point> residentList = new LinkedList<Point>();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.arg1 == 1 && msg.arg2 ==1){
                synthesizerManager.play("30分钟后开始任务");
                DialogUtil.newTaskDialog(TaskActivity.this,orderList.get(0).routeName,FormatUtil.getTime3(orderList.get(0).startTime, orderList.get(0).endTime),null);
            }else if(msg.arg1 == 1 && msg.arg2 ==2){
                Message message = Message.obtain();
                message.what = 2;
                mHandler.sendMessageDelayed(message, 30000);
            }else if(msg.arg1 == 2 && msg.arg2 ==1){
                synthesizerManager.play("30分钟后开始任务");
                DialogUtil.newTaskDialog(TaskActivity.this,orderList.get(1).routeName,FormatUtil.getTime3(orderList.get(1).startTime, orderList.get(1).endTime),null);
            }else if(msg.arg1 == 2 && msg.arg2 ==2){
                synthesizerManager.play("任务开始");
                mPresenter.getTaskList();
                DialogUtil.taskBeginDialog(TaskActivity.this,orderList.get(1).routeName, FormatUtil.getTime3(orderList.get(1).startTime, orderList.get(1).endTime), orderList.get(1).endTime,null);
            }
            if(msg.what == 2){
                synthesizerManager.play("任务开始");
                DialogUtil.taskBeginDialog(TaskActivity.this,orderList.get(0).routeName, FormatUtil.getTime3(orderList.get(0).startTime, orderList.get(0).endTime), orderList.get(0).endTime,null);
                mPresenter.getTaskList();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
       rtspMenager.updateChatGroup();
    }

    @Override
    protected int getLayout() {
        Logger.d("000000000");
        return R.layout.activity_main;
    }


    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        startLacationService();
        bindServer();
        initData();
        initManager();
        registerBatteryReceiver();
        tv_name.setText(App.userBean.empName+"("+App.userBean.empNum+")");
        mPresenter.getTaskList();
        NetworkUtil.getCellularSignalStrength();
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void showLoading(String title) {}

    @Override
    public void stopLoading() {}

    @Override
    public void showErrorTip(String msg) {}

    @Override
    public void returnTaskList(List<TaskBean> taskList, List<TaskBean> orderList) {
        Logger.d("returnTaskList");
        this.taskList = taskList;
        this.orderList = orderList;
        clearTimeTask();
        initViewData();
    }

    @Override
    public void returnAlarm(String type) {
        switch (Integer.valueOf(type)) {
            case -1:
                stopICE();
                callIce();
                break;

            case 1:
                normalAlarm();
                break;

            case 2:
                quietlyAlarm();
                break;
            case 3:
                automaticAlarm();
                break;

            default:
                break;
        }
    }

    @Override
    public void returnVideo(VideoBean videobean) {
        Gson gson = new Gson();
        final String videoString = gson.toJson(videobean);
        new VideoDataBO(TaskActivity.this).updateVideoData(videoString);
    }

    @OnClick({R.id.ll_being_task1,R.id.ll_being_task2,R.id.ib_task_more})
    void onclick(View v){
        switch (v.getId()) {

            case R.id.ll_being_task1:
                custom_locationview1.setVisibility(custom_locationview1.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                break;

            case R.id.ll_being_task2:
                custom_locationview2.setVisibility(custom_locationview2.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                break;

            case R.id.ib_task_more:
                startActivity(SettingsActivity.class);
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        /*if(isAlarm) return super.onKeyDown(keyCode, event); */
        switch (keyCode) {
            case 137:      //电击
                if(isAlarm || isLock || isSpeak) return true;
                DialogUtil.amartmateDialog(TaskActivity.this);
                return true;

            case KeyEvent.KEYCODE_CAMERA:
                if(isAlarm || isLock || isSpeak) return true;
                event.startTracking();
                if(event.getRepeatCount() == 0){
                    shortPress = true;
                }
                return true;

            case KeyEvent.KEYCODE_BACK:
                if(isLock  || isSpeak) return true;
                event.startTracking();
                if(event.getRepeatCount() == 0){
                    shortPress = true;
                }

            case 5:  //PTT
                Logger.d("KEYCODE_F9--short");
                if(isAlarm || isLock) return true;
                event.startTracking();
                if(event.getRepeatCount() == 0){
                    shortPress = true;
                }
                return true;

            case KeyEvent.KEYCODE_F10:  //SOS
                if(isAlarm || isLock || isSpeak) return true;
                event.startTracking();
                if(event.getRepeatCount() == 0){
                    shortPress = true;
                }
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_F10:
                shortPress = false;
                mPresenter.sendAlarm("2");
                return true;

            case KeyEvent.KEYCODE_CAMERA:
                shortPress = false;
                takeVideo();
                return true;

            case KeyEvent.KEYCODE_BACK:
                shortPress = false;
                if(isAlarm){
                    Logger.d("KEYCODE_BACK----long");
                    cancelAlarm();
                    mPresenter.cancelAlarm(App.alarmNum);
                    isAlarm = false;
                }

                return true;
            case 5 :
            /*case KeyEvent.KEYCODE_F9:  //PTT*/
                isSpeak = true;
                Logger.d("KEYCODE_F9--long");
                return rtspMenager.down();
        }
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_F10:
                if(shortPress){
                    mPresenter.sendAlarm("1");
                    Logger.d("正常报警");
                }
                shortPress = false;
                return true;

            case KeyEvent.KEYCODE_CAMERA:
                if(shortPress){
                    takePicture();
                }
                shortPress = false;
                return true;

            case KeyEvent.KEYCODE_BACK:
                if(isAlarm) return true;
                if(shortPress){
                    onBackPressed();
                    Logger.d("KEYCODE_BACK-----short");
                }
                shortPress = false;
                return true;

            case 5:  //PTT
                Logger.d("KEYCODE_F9--up");
                isSpeak = false;
                rtspMenager.up();
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            switch (requestCode) {
                case TAKEPHOTO:
                    if (resultCode == RESULT_OK) {
                        mPresenter.submitFile(imag_path, "photo");
                    }
                    break;
                case TAKEVIDEO:
                    addVideoBD(video_path);
                    if(NetworkUtil.getCurrentNetworkType() == 0x05 || NetworkUtil.getCurrentNetworkType() == 0x04){
                        sendVideo();
                    }
                    mPresenter.submitFile(video_path, "video");
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        lognout();
        finish();
    }


    private void lognout(){
        Intent intent = new Intent();
        intent.setAction("com.smartmate.action.LOGOUT");
        sendBroadcast(intent);
        App.cancelAccount();
        ToastUtil.showShort("登出成功");
        removeAll();

    }

    private void initData(){
        iceList = App.barCodeBean.iceNums;
        cache = CacheDeta.getInstance();
        isLock = SPUtil.getSharedBooleanData("isLock");
        if(isLock){
            locking();
        }
    }

    private void initManager(){
        synthesizerManager =  SynthesizerManager.getInstatce(this);
        audioManager = AudioManagerUtil.getInstance(this);
        rtspMenager = RtspMenager.getInstance(this);
    }

    private void registerBatteryReceiver(){
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryReceiver, intentFilter);
    }

    private void initViewData(){
        int taskCount = taskList.size();
        int orderCount = orderList.size();

        if(taskCount >= 2){
            tv_task_empty.setVisibility(View.GONE);
            ll_being_task1.setVisibility(View.VISIBLE);
            ll_being_task2.setVisibility(View.VISIBLE);
            initBingTaskData1(taskList.get(0));
            initBingTaskData2(taskList.get(1));
        }else if(taskCount == 1){
            tv_task_empty.setVisibility(View.GONE);
            ll_being_task1.setVisibility(View.VISIBLE);
            ll_being_task2.setVisibility(View.GONE);
            initBingTaskData1(taskList.get(0));
        }else{
            tv_task_empty.setVisibility(View.VISIBLE);
            ll_being_task1.setVisibility(View.GONE);
            ll_being_task2.setVisibility(View.GONE);
        }
        if(orderCount >= 2){
            ll_task1.setVisibility(View.VISIBLE);
            ll_task2.setVisibility(View.VISIBLE);
            initTaskData1(orderList.get(0));
            initTaskData2(orderList.get(1));
        }else if(orderCount == 1){
            ll_task1.setVisibility(View.VISIBLE);
            ll_task2.setVisibility(View.GONE);
            initTaskData1(orderList.get(0));
        }else{
            ll_task1.setVisibility(View.GONE);
            ll_task2.setVisibility(View.GONE);
        }
        if(taskCount > 0 || orderCount > 0){
            tv_task_empty.setVisibility(View.GONE);
        }else{
            tv_task_empty.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 正在执行的任务1
     */
    private void initBingTaskData1(TaskBean task){
        int a = 0;
        for (int i = 0; i < task.sites.size(); i++) {
            if(task.sites.get(i).state == 1){
                a += 1;
            }
        }
        String percent = "("+a+"/"+task.sites.size()+")";
        long[] times = FormatUtil.getTimeDif(task.endTime);
        ttv_being_task_time1.setTimes(times);
        Logger.d("时间="+ttv_being_task_time1.getTextSize());
        tv_being_task_route1.setText(task.routeName);
        tv_being_task_route1.getTextSize();
        Logger.d("路线="+tv_being_task_route1.getTextSize());
        tv_being_task_percentage1.setText(percent);
        tv_being_task_time1.setText(FormatUtil.getTime3(task.startTime, task.endTime));
        if(!ttv_being_task_time1.isRun()){
            ttv_being_task_time1.beginRun();
        }
        ttv_being_task_time1.setTimeout(new TimeEnd() {
            @Override
            public void timeEnd() {
                synthesizerManager.play("任务超时");
                Logger.d("任务超时----"+Thread.currentThread().getName());
                taskList.remove(0);
                App.taskBean = null;
                initViewData();
            }
        });
        custom_locationview1.setData(sortTaskList(task.sites));
    }


    /**
     * 正在执行的任务2
     */
    private void initBingTaskData2(TaskBean task){
        int a = 0;
        for (int i = 0; i < task.sites.size(); i++) {
            if(task.sites.get(i).state == 1){
                a += 1;
            }
        }

        String percent = "("+a+"/"+task.sites.size()+")";
        long[] times = {10,5,30};
        times = FormatUtil.getTimeDif(task.endTime);
        ttv_being_task_time2.setTimes(times);
        tv_being_task_route2.setText(task.routeName);
        tv_being_task_percentage2.setText(percent);
        tv_being_task_time2.setText(FormatUtil.getTime3(task.startTime, task.endTime));
        if(!ttv_being_task_time2.isRun()){
            ttv_being_task_time2.beginRun();
        }
        ttv_being_task_time2.setTimeout(new TimeEnd() {
            @Override
            public void timeEnd() {
                synthesizerManager.play("任务超时");
                if(taskList.size() == 2) {
                    taskList.remove(1);
                }else if(taskList.size() == 1){
                    taskList.remove(0);
                }
                initViewData();
            }
        });
        custom_locationview2.setData(sortTaskList(task.sites));
    }


    private void closedTaskTime(){
        if(ttv_being_task_time1.isRun()){
            ttv_being_task_time1.stop();
        }
        if(ttv_being_task_time2.isRun()){
            ttv_being_task_time2.stop();
        }
    }
    /**
     * 即将开始的任务1
     */
    private void initTaskData1(TaskBean task){
        tv_task_route1.setText(task.routeName);
        tv_task_time1.setText(FormatUtil.getTime3(task.startTime, task.endTime));
        timeTask(1,task.startTime);
    }

    /**
     * 即将开始的任务2
     */
    private void initTaskData2(TaskBean task){
        tv_task_route2.setText(task.routeName);
        tv_task_time2.setText(FormatUtil.getTime3(task.startTime, task.endTime));
        timeTask(2,task.startTime);
    }

    private void reflushPercentageView(TaskBean task){
        int a = 0;
        for (int i = 0; i < task.sites.size(); i++) {
            if(task.sites.get(i).state == 1){
                a += 1;
            }
        }
        if( a == task.sites.size()){
            App.taskBean = null;
            taskList.clear();
            clearTimeTask();
            initViewData();
//            DialogUtil.taskFinishDialog(this,taskList.get(i).routeName, FormatUtil.getTime3(taskList.get(0).startTime,taskList.get(0).endTime), FormatUtil.getTime3(taskList.get(0).startTime),null);
        }
        String percent = "("+a+"/"+task.sites.size()+")";
        tv_being_task_percentage1.setText(percent);
    }
    /**
     * 开启定位服务
     */
    private void startLacationService(){
        this.startService(new Intent(this,LocationService.class));
        this.startService(new Intent(this,GuardService.class));
    }

    private void bindServer() {
        conn = new Conn();
        Intent intent = new Intent(this, LoopCallService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

    /**
     * 拍照
     */
    private void takePicture(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File dir = new File(ConstantsValue.path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        file = new File(ConstantsValue.path, FormatUtil.getMedioName()+".jpg");
        imag_path = file.getAbsolutePath();
        Uri photo_uri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photo_uri);
        startActivityForResult(intent, TAKEPHOTO);
    }

    /**
     * 录视频
     *
     */
    private void takeVideo(){
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        File file = new File(ConstantsValue.path, FormatUtil.getMedioName()+".mp4");
        video_path = file.getAbsolutePath();
        Uri uri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, TAKEVIDEO);
    }

    /**
     * 正常报警
     */
    private void normalAlarm(){
        ToastUtil.showShort("普通报警开启");
        rtspMenager.sendToServer("TB_ALARM",false,1,App.alarmNum);//直接告诉值班员有人报警
        takeVideo();
        startIce();
    }

    /**
     * 寂静报警
     */
    private void quietlyAlarm(){
        isAlarm = true;
/*        ToastUtil.showShort("静寂报警开启");*/
        rtspMenager.sendToServer("TB_ALARM",false,2,App.alarmNum);//直接告诉值班员有人报警
        rtspMenager.startPushAudioStream(UrlValue.streamUrl+"/"+App.userBean.empNum+".sdp");
        audioManager.setMinVolume();
        tv_quiet_alram.setVisibility(View.VISIBLE);
        tv_quiet_alram.setText("静寂报警中");
        startIce();
    }

    /**
     * 自动报警
     */
    private void automaticAlarm(){
        isAutom = true;
        startIce();
        rtspMenager.sendToServer("TB_ALARM",false,3,App.alarmNum);//直接告诉值班员有人报警
    }

    private void isResident(){
        if(DistanceUtil.isResident(residentList)){
            residentList.clear();
            mPresenter.sendAlarm("3");
        }
    }

    private void addResidentList(){
        if(isAutom) return;
        residentList.add(App.mPoint);
        if(residentList.size()>=  ConstantsValue.autoSize){
            residentList.remove(0);
            isResident();
        }
    }

    /**
     * 取消报警
     */
    private void cancelAlarm(){
        isAlarm = false;
        isAutom = false;
        rtspMenager.stopPushAudioStream();
        audioManager.setMaxVolume();
        tv_quiet_alram.setVisibility(View.GONE);
        stopICE();
    }


    /**
     * 停止ICE计时
     */
    private void stopICE(){
        isICEStart = false;
        if(alarmTask != null){
            alarmTask.cancel();
            alarmTask = null;
        }
    }
    /**
     * 开始ICE计时
     */
    private void startIce(){
        if(!isICEStart){
            if(alarmTask == null){
                alarmTask = new AlarmTask();
            }
            timer.schedule(alarmTask, App.barCodeBean.getIceNumTime());
            isICEStart = true;
        }
    }

    /**
     * 拨打ICE电话
     */
    private void callIce(){
        isICEStart = false;
        isAlarm = false;
        isAutom = false;
        mBinder.call();

    }

    /**
     * @param path
     * 存视频
     */
    private void addVideoBD(String path){
        VideoBean videoBean = new VideoBean();
        String strTaskNum = App.taskBean == null ? "v" + App.USERID : App.taskBean.taskNum;
        videoBean.setPath(path);
        videoBean.setEmpNum(App.userBean.empNum);
        videoBean.setLa(String.valueOf(App.mPoint.la));
        videoBean.setLo(String.valueOf(App.mPoint.lo));
        if(App.taskBean != null){
            videoBean.setTaskNum(App.taskBean.taskNum);
        }else{
            videoBean.setTaskNum(strTaskNum);
        }
        if(App.alarmNum != null){
            videoBean.setAlarmNum(App.alarmNum);
        }
        videoBean.setUploadTime(FormatUtil.getPointDate());
        Gson gson = new Gson();
        String videoString=gson.toJson(videoBean);
        new VideoDataBO(this).insertVideoData(videoString);
    }

    /**
     * 底部跑马灯
     */
    private void handleScrollTextView(String str){
        autoScrollTextView.initScrollTextView(this.getWindowManager(), str);
        autoScrollTextView.starScroll();
    }


    public void timeTask(int num1,String time) {
        clearTimeTask();
        if(num1 == 1){
            if(FormatUtil.getTime4(time) >0){
                listTask.add(new Task(1,1,FormatUtil.getTime4(time)));
            }
            if(FormatUtil.getTime5(time) >0){
                listTask.add(new Task(1,2,FormatUtil.getTime5(time)));
            }
        }else{
            if(FormatUtil.getTime4(time) >0){
                listTask.add(new Task(2,1,FormatUtil.getTime4(time)));
            }
            if(FormatUtil.getTime5(time) >0){
                listTask.add(new Task(2,2,FormatUtil.getTime5(time)));
            }
        }
        for(Task task : listTask) {
            timer.schedule(task, task.getDifTime());
        }
    }

    public void clearTimeTask(){
        for (Task task : listTask) {
            task.cancel();
        }
        listTask.clear();
       /* App.taskBean = null;*/
    }

    /**
     * 上传位置信息
     */
    private void submitData(){
        final List<String> list = new LocationDataBO(this).queryLocationData();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (String string : list) {
                    mPresenter.submitLocation(string);
                }
            }
        }).start();
    }

    /**
     * wifi传本地视频
     */
    private void sendVideo(){
        List<String> videoList = new VideoDataBO(this).queryVideoData();
        for (String video : videoList) {
            VideoBean videobean = GsonUtil.jsonToBean(video, VideoBean.class);
            mPresenter.submitVideo(videobean);
        }
    }

    private void handleNoNetwork(){
        synthesizerManager.play("当前无网络");
        if(isSpeak){
            isSpeak = false;
            rtspMenager.up();
        }

    }

    /**
     * 对保护点列表排序显示
     */
    private List sortTaskList(List<PatrolPointBean> list){
        List<PatrolPointBean> listfinish = new ArrayList<PatrolPointBean>();
        List<PatrolPointBean> listUnfinish = new ArrayList<PatrolPointBean>();
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).state == 1){
                listfinish.add(list.get(i));
            }else{
                listUnfinish.add(list.get(i));
            }
        }
        this.listUnfinish = listUnfinish;
        list.clear();
        list.addAll(listUnfinish);
        list.addAll(listfinish);
        listfinish.clear();
        listUnfinish.clear();
        return list;
    }

    private void logout(){
        App.cancelAccount();
        ToastUtil.showShort("您已在另一台机器上登陆");
        removeAll();
        startActivity(FirstActivity.class);
    }

    /**
     * EventBus消息处理
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShowMessageEvent(MessageEvent messageEvent) {
        switch (messageEvent.getType()) {
            case TYPE_PUSH:
                handlePushMsg(messageEvent);
                break;
            case TYPE_NETWORK:
            case TYPE_NETWORK_WIFI:
                if((System.currentTimeMillis()-exitTime) > 4000){
                    synthesizerManager.play("网络恢复正常");
                    submitData();
                    sendVideo();
                    exitTime = System.currentTimeMillis();
                }
                break;

            case TYPE_NO_NETWORK:
                handleNoNetwork();
                break;

            case TYPE_LOGOUT:
                logout();
                break;
            case TYPE_SCREEM_LOCK:
                break;

            case TYPE_ONLINE:
                rl_title.setBackgroundColor(getResources().getColor(R.color.statebar_color));

                break;

            case TYPE_DROPPED:
                rl_title.setBackgroundColor(Color.rgb(247, 98, 72));
                break;

            case TYPE_DEL_DEV:
               /* SPUtil.setSharedIntData("first", -1);
                startActivity(FirstActivity.class);*/
                SPUtil.setSharedIntData("first",0);
                finish();
                Logger.d("TYPE_DEL_DEV---------");
                break;

            case TYPE_LOCK_DEV:

                break;

            case TYPE_SERVICELOCATION:
                if(App.taskBean != null){
                    addResidentList();
                }

                tv_radius.setText(App.radius+"");
                if(App.radius < 50){
                    iv_weixing.setImageResource(R.drawable.ic_weixing_on);
                }else{
                    iv_weixing.setImageResource(R.drawable.ic_weixing_off);
                }
                int size = taskList.size();
                if(size == 0){
                    break;
                }
                List<PatrolPointBean> sites = taskList.get(0).sites;
                List<FinishedPoint> finishedPointlist = new ArrayList<FinishedPoint>();
                for(int i = 0; i< size; i++){
                    for (int j = 0; j < sites.size(); j++) {
                        if(sites.get(j).state == 1 || sites.get(j).state == 2){
                            continue;
                        }
                        double ditance = DistanceUtil.getDistance(sites.get(j).clola, App.mPoint);
                        if(ditance < sites.get(j).errorRadius){
                            sites.get(j).state = 1;
                            FinishedPoint finishedPoint = new FinishedPoint();
                            finishedPoint.setPatrolTime(FormatUtil.getTime2());
                            finishedPoint.setSiteNum(sites.get(j).siteNum);
                            finishedPoint.setSiteName(sites.get(j).siteName);
                            finishedPoint.setTaskNum(taskList.get(i).taskNum);
                            finishedPointlist.add(finishedPoint);
                            mPresenter.submitFinishedPoint(finishedPoint);
                            synthesizerManager.play(sites.get(j).siteName+"已完成");
                            reflushPercentageView(taskList.get(i)); //更新完成进度控件
                            custom_locationview1.setData(sortTaskList(sites));
                            if(finishedPointlist.size() == sites.size()){
                                App.taskBean = null;
                                taskList.clear();
                                clearTimeTask();
                                initViewData();
                                DialogUtil.taskFinishDialog(this,taskList.get(i).routeName, FormatUtil.getTime3(taskList.get(0).startTime,taskList.get(0).endTime), FormatUtil.getTime3(taskList.get(0).startTime),null);
                            }
                        }
                    }
                }
                break;
            default:
                break;
        }
    }




    /**
     * @param messageEvent
     * 推送消息处理
     */
    private void handlePushMsg(MessageEvent messageEvent){
        String msg = messageEvent.getMessage();
        String extra = messageEvent.getExtra();
        PushExtrasDataBean extrasBean = GsonUtil.jsonToBean(extra, PushExtrasDataBean.class);
        String type = extrasBean.type;
        Logger.d(msg+"-----"+type);
        if(!(isAlarm || TextUtils.equals("modifyConfig", type))){
            synthesizerManager.play(msg);
        }
        if(TextUtils.equals("lamp", type)){
            handleScrollTextView(msg);
        }

        switch (type){
            case "extraTime":
                delayedTask();
                break;
            case "cancelTask":
                stopTask();
                break;
            case "newTask":
                distributeTask(extra);
                break;
            case "lockDevice":
                locking();
                break;
            case "changeBand":
                binding();
                break;
            case "unlockDevice":
                unLocking();
                break;
            case "handleAlarm":
                cancelAlarm();
                break;
            case "modifyConfig":
                modifyConfig();
                break;
            case "bandEmp":
                modifyband();
                break;
        }
    }

    /**
     * 修改配置信息
     */
    public void modifyConfig(){
        startActivity(FirstActivity.class);
        finish();
    }

    /**
     * 修改绑定
     */
    public void modifyband(){
        startActivity(FirstActivity.class);
        finish();
    }

    /**
     * 中止任务
     */
    public void stopTask(){
        clearTimeTask();
        //		initViewData();
        App.taskBean = null;
        mPresenter.getTaskList();
    }

    /**
     * 任务延时
     */
    public void delayedTask(){
        mPresenter.getTaskList();
    }

    /**
     * 任务派发
     */
    public void distributeTask(String extra){
        JSONObject obj_result;
        String routeName = null;
        String timeStr = null;
        try {
            obj_result = new JSONObject(extra);
            routeName = obj_result.optString("routeName");
            timeStr = obj_result.optString("timeStr");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mPresenter.getTaskList();
    }

    /**
     *机身锁定通知
     */
    public void locking(){
        isLock = true;
        SPUtil.setSharedBooleanData("isLock", isLock);
        tv_quiet_alram.setText("设备锁定了");
        tv_quiet_alram.setVisibility(View.VISIBLE);
    }

    /**
     *机身锁定解锁通知
     */
    public void unLocking(){
        isLock = false;
        SPUtil.setSharedBooleanData("isLock", isLock);
        tv_quiet_alram.setVisibility(View.GONE);
    }

    /**
     * 其他通知
     */
    public void otherNotice(){

    }

    public void binding(){
        startActivity(FirstActivity.class);
        finish();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        closedTaskTime();
        clearTimeTask();
        stopICE();
        rtspMenager.stopPushAudioStream();
        rtspMenager.disconnect();
        if(conn != null){
            try{
                unbindService(conn);
            }catch (Exception e){
                Logger.d(e.toString());
            }

        }
        if(batteryReceiver != null){
            unregisterReceiver(batteryReceiver);
        }
        EventBus.getDefault().unregister(this);
    }


    class Task extends TimerTask {
        private int num1;
        private int num2;
        private long difTime;

        public Task(int num1,int num2,long difTime){
            this.num1 = num1;
            this.num2 = num2;
            this.difTime = difTime;
        }
        public long getDifTime(){
            return difTime;
        }
        @Override
        public void run() {
            Message message = Message.obtain();
            message.arg1 = num1;
            message.arg2 = num2;
            mHandler.sendMessage(message);
        }
    }

    class AlarmTask extends TimerTask{
        @Override
        public void run() {
            callIce();
        }
    }

    class Conn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBinder = (LoopCallService.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}
